using DocumentCreationSystem.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Net.Http;
using System.Text.RegularExpressions;

namespace DocumentCreationSystem.Services;

/// <summary>
/// AI服务管理器，统一管理多个AI服务提供者
/// </summary>
public class AIServiceManager : IAIService
{
    private readonly IConfiguration _configuration;
    private readonly ILogger<AIServiceManager> _logger;
    private readonly IThinkingChainService _thinkingChainService;
    private readonly IServiceProvider? _serviceProvider;
    private readonly Dictionary<string, IAIService> _providers;
    private IAIService? _currentProvider;
    private AIModel? _currentModel;
    private bool _enableThinkingChainProcessing;
    private DateTime _lastHealthCheck = DateTime.MinValue;
    private readonly TimeSpan _healthCheckInterval = TimeSpan.FromMinutes(5); // 每5分钟检查一次健康状态

    // 配置缓存（预留用于未来功能扩展）
    // private AIModelConfig? _cachedConfig;
    // private DateTime _lastConfigLoadTime = DateTime.MinValue;
    // private readonly TimeSpan _configCacheTimeout = TimeSpan.FromMinutes(5);

    public AIServiceManager(IConfiguration configuration, ILogger<AIServiceManager> logger, IThinkingChainService thinkingChainService, IServiceProvider? serviceProvider = null)
    {
        _configuration = configuration;
        _logger = logger;
        _thinkingChainService = thinkingChainService;
        _serviceProvider = serviceProvider;
        _providers = new Dictionary<string, IAIService>();

        // 从配置文件读取思维链处理设置
        _enableThinkingChainProcessing = _configuration.GetValue<bool>("AI:EnableThinkingChain", true);
        _logger.LogInformation($"思维链处理状态: {(_enableThinkingChainProcessing ? "启用" : "禁用")}");
    }

    /// <summary>
    /// 初始化AI服务提供者
    /// </summary>
    public async Task InitializeProvidersAsync()
    {
        try
        {
            _logger.LogInformation("开始初始化AI服务提供者...");

            // 初始化Ollama服务
            var ollamaConfig = _configuration.GetSection("AI:Ollama");
            if (ollamaConfig.Exists() && !string.IsNullOrEmpty(ollamaConfig["BaseUrl"]))
            {
                var ollamaService = new OllamaService(ollamaConfig, _logger);
                _providers["Ollama"] = ollamaService;
                _logger.LogInformation("Ollama服务已初始化");
            }

            // 初始化LM Studio服务
            var lmStudioConfig = _configuration.GetSection("AI:LMStudio");
            if (lmStudioConfig.Exists() && !string.IsNullOrEmpty(lmStudioConfig["BaseUrl"]))
            {
                var lmStudioService = new LMStudioService(lmStudioConfig, _logger);
                _providers["LMStudio"] = lmStudioService;
                _logger.LogInformation("LM Studio服务已初始化");
            }

            // 初始化智谱AI服务
            var zhipuConfig = _configuration.GetSection("AI:ZhipuAI");
            if (zhipuConfig.Exists() && !string.IsNullOrEmpty(zhipuConfig["ApiKey"]))
            {
                var zhipuService = new ZhipuAIService(zhipuConfig, _logger);
                _providers["ZhipuAI"] = zhipuService;
                _logger.LogInformation("智谱AI服务已初始化");
            }

            // 初始化DeepSeek服务
            var deepSeekConfig = _configuration.GetSection("AI:DeepSeek");
            if (deepSeekConfig.Exists() && !string.IsNullOrEmpty(deepSeekConfig["ApiKey"]))
            {
                var deepSeekService = new DeepSeekService(deepSeekConfig, _logger);
                _providers["DeepSeek"] = deepSeekService;
                _logger.LogInformation("DeepSeek服务已初始化");
            }

            // 初始化OpenAI服务
            var openAIConfig = _configuration.GetSection("AI:OpenAI");
            if (openAIConfig.Exists())
            {
                var openAIService = new OpenAIService(openAIConfig, _logger);
                _providers["OpenAI"] = openAIService;
                _logger.LogInformation("OpenAI服务已初始化");
            }

            // 初始化Alibaba服务
            var alibabaConfig = _configuration.GetSection("AI:Alibaba");
            if (alibabaConfig.Exists() && !string.IsNullOrEmpty(alibabaConfig["ApiKey"]))
            {
                var alibabaService = new AlibabaService(alibabaConfig, _logger);
                _providers["Alibaba"] = alibabaService;
                _logger.LogInformation("Alibaba服务已初始化");
            }

            // 初始化RWKV服务
            var rwkvConfig = _configuration.GetSection("AI:RWKV");
            if (rwkvConfig.Exists() && !string.IsNullOrEmpty(rwkvConfig["BaseUrl"]))
            {
                var httpClient = _serviceProvider?.GetService<HttpClient>() ?? new HttpClient();
                var rwkvService = new RWKVService(_logger as ILogger<RWKVService>, httpClient);
                var config = new RWKVConfig
                {
                    BaseUrl = rwkvConfig["BaseUrl"] ?? "http://localhost:8000",
                    ApiKey = rwkvConfig["ApiKey"] ?? "",
                    SelectedModel = rwkvConfig["SelectedModel"] ?? "RWKV-6-World-3B"
                };
                rwkvService.UpdateConfig(config);
                _providers["RWKV"] = rwkvService;
                _logger.LogInformation("RWKV服务已初始化");
            }

            // 设置默认提供者
            if (_providers.Any())
            {
                _currentProvider = _providers.Values.First();
                _logger.LogInformation($"使用第一个可用的AI提供者: {_providers.Keys.First()}");
            }
            else
            {
                _logger.LogWarning("没有可用的AI服务提供者");
            }

            _logger.LogInformation($"AI服务提供者初始化完成，共初始化 {_providers.Count} 个提供者");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "初始化AI服务提供者失败");
        }
    }

    /// <summary>
    /// 设置当前AI服务提供者
    /// </summary>
    public async Task<bool> SetCurrentProviderAsync(string providerName)
    {
        if (_providers.ContainsKey(providerName))
        {
            _currentProvider = _providers[providerName];
            _logger.LogInformation($"切换到AI提供者: {providerName}");
            return true;
        }

        _logger.LogWarning($"AI提供者 {providerName} 不存在");
        return false;
    }

    /// <summary>
    /// 获取当前提供者名称
    /// </summary>
    public string GetCurrentProviderName()
    {
        if (_currentProvider == null) return "无";
        
        return _providers.FirstOrDefault(p => p.Value == _currentProvider).Key ?? "未知";
    }

    /// <summary>
    /// 生成文本
    /// </summary>
    public async Task<string> GenerateTextAsync(string prompt, int maxTokens = 1000, float temperature = 0.7f)
    {
        if (_currentProvider == null)
        {
            throw new InvalidOperationException("没有可用的AI服务提供者");
        }

        try
        {
            // 在生成前检查服务状态
            await EnsureServiceAvailableAsync();

            // 添加思维链格式指导
            var enhancedPrompt = AddThinkingChainGuidance(prompt);

            var result = await _currentProvider.GenerateTextAsync(enhancedPrompt, maxTokens, temperature);

            // 处理思维链响应
            if (_enableThinkingChainProcessing)
            {
                var filter = new ThinkingChainFilter
                {
                    EnableFilter = true,
                    Mode = FilterMode.RemoveThinkingChain
                };

                var processedResult = _thinkingChainService.ProcessThinkingChainResponse(result, filter);
                return processedResult.ProcessedContent;
            }

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"生成文本失败，提供者: {GetCurrentProviderName()}");

            // 尝试自动恢复服务
            if (await TryRecoverServiceAsync(ex))
            {
                _logger.LogInformation("服务恢复成功，重试生成文本");
                // 递归重试一次
                return await GenerateTextAsync(prompt, maxTokens, temperature);
            }

            throw;
        }
    }

    /// <summary>
    /// 获取可用模型列表
    /// </summary>
    public async Task<List<AIModel>> GetAvailableModelsAsync()
    {
        if (_currentProvider == null)
        {
            return new List<AIModel>();
        }

        try
        {
            return await _currentProvider.GetAvailableModelsAsync();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"获取可用模型失败，提供者: {GetCurrentProviderName()}");
            return new List<AIModel>();
        }
    }

    /// <summary>
    /// 设置当前模型
    /// </summary>
    public async Task<bool> SetCurrentModelAsync(string modelId)
    {
        if (_currentProvider == null)
        {
            _logger.LogWarning("没有可用的AI服务提供者");
            return false;
        }

        try
        {
            var success = await _currentProvider.SetCurrentModelAsync(modelId);
            if (success)
            {
                _currentModel = _currentProvider.GetCurrentModel();
                _logger.LogInformation($"设置当前模型成功: {modelId}");
            }
            return success;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"设置当前模型失败: {modelId}");
            return false;
        }
    }

    /// <summary>
    /// 获取当前模型
    /// </summary>
    public AIModel? GetCurrentModel()
    {
        return _currentModel ?? _currentProvider?.GetCurrentModel();
    }

    /// <summary>
    /// 生成章节内容
    /// </summary>
    public async Task<string> GenerateChapterAsync(string outline, string? context = null, int targetWordCount = 6500)
    {
        if (_currentProvider == null)
        {
            throw new InvalidOperationException("没有可用的AI服务提供者");
        }

        try
        {
            var prompt = $"根据以下大纲和上下文，生成约{targetWordCount}字的章节内容：\n\n大纲：\n{outline}\n\n上下文：\n{context ?? "无"}\n\n请生成完整的章节内容：";
            
            // 添加思维链格式指导
            var enhancedPrompt = AddThinkingChainGuidance(prompt);
            
            var result = await _currentProvider.GenerateTextAsync(enhancedPrompt, targetWordCount * 2, 0.8f);
            
            // 首先使用简单的思维链过滤
            var preliminaryFiltered = _thinkingChainService.FilterThinkingChain(result);

            // 处理思维链响应
            if (_enableThinkingChainProcessing)
            {
                var filter = new ThinkingChainFilter
                {
                    EnableFilter = true,
                    Mode = FilterMode.RemoveThinkingChain
                };

                var processedResult = _thinkingChainService.ProcessThinkingChainResponse(preliminaryFiltered, filter);
                var filteredContent = processedResult.ProcessedContent;

                // 进一步过滤章节内容中的非小说正文部分
                filteredContent = _thinkingChainService.FilterChapterContent(filteredContent);

                // 验证内容质量
                filteredContent = ValidateAndCleanChapterContent(filteredContent);

                return filteredContent;
            }

            // 即使没有启用思维链处理，也要过滤非小说正文内容
            var cleanedContent = _thinkingChainService.FilterChapterContent(preliminaryFiltered);

            // 验证内容质量
            cleanedContent = ValidateAndCleanChapterContent(cleanedContent);

            return cleanedContent;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "生成章节内容失败");
            throw;
        }
    }

    /// <summary>
    /// 验证和清理章节内容
    /// </summary>
    private string ValidateAndCleanChapterContent(string content)
    {
        if (string.IsNullOrEmpty(content))
            return content;

        var cleanedContent = content;

        // 移除错误信息和占位符
        var errorPatterns = new[]
        {
            @"由于您提供的.*?缺少具体的情节描述.*?请您补充完整章节的相关信息后再提出请求。",
            @"<\|begin_of_box\|>.*?<\|end_of_box\|>",
            @"（此处为完整的第.*?章小说章节内容.*?）",
            @"\*\*（此处省略.*?\)\*\*",
            @"（此处省略.*?）",
            @"此处省略部分重复内容",
            @"【.*?】", // 移除方括号注释
            @"〖.*?〗"  // 移除花括号注释
        };

        foreach (var pattern in errorPatterns)
        {
            cleanedContent = Regex.Replace(cleanedContent, pattern, "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
        }

        // 移除大纲式标题
        var outlinePatterns = new[]
        {
            @"^###?\s*.*?$",
            @"^\*\*.*?\*\*$",
            @"^第.*?章.*?$",
            @"^章节.*?：.*?$"
        };

        foreach (var pattern in outlinePatterns)
        {
            cleanedContent = Regex.Replace(cleanedContent, pattern, "", RegexOptions.Multiline | RegexOptions.IgnoreCase);
        }

        // 清理多余的空行
        cleanedContent = Regex.Replace(cleanedContent, @"\n\s*\n\s*\n", "\n\n", RegexOptions.Multiline);
        cleanedContent = Regex.Replace(cleanedContent, @"^\s+", "", RegexOptions.Multiline);

        return cleanedContent.Trim();
    }

    /// <summary>
    /// 为提示词添加思维链格式指导
    /// </summary>
    private string AddThinkingChainGuidance(string originalPrompt)
    {
        if (!_enableThinkingChainProcessing)
        {
            return originalPrompt;
        }

        var guidance = BuildThinkingChainGuidance();
        return originalPrompt + guidance;
    }

    /// <summary>
    /// 构建思维链格式指导文本
    /// </summary>
    private string BuildThinkingChainGuidance()
    {
        return @"

请按照以下格式回复：
1. 如果需要思考过程，请将思考内容放在 <think>...</think> 标签中
2. 将最终答案放在 <output>...</output> 或 <o>...</o> 标签中
3. 只有 <output> 或 <o> 标签中的内容会被显示给用户
4. 支持多种思维链格式：<think>、<thinking>、或 Qwen 格式的 ...</think>

示例格式：
<think>
这里是我的思考过程...
分析问题的各个方面...
</think>

<output>
这里是最终的回答内容
</output>";
    }

    /// <summary>
    /// 设置思维链处理状态
    /// </summary>
    public void SetThinkingChainProcessing(bool enabled)
    {
        _enableThinkingChainProcessing = enabled;
    }

    /// <summary>
    /// 获取思维链处理状态
    /// </summary>
    public bool IsThinkingChainProcessingEnabled()
    {
        return _enableThinkingChainProcessing;
    }

    /// <summary>
    /// 获取思维链服务
    /// </summary>
    public IThinkingChainService GetThinkingChainService()
    {
        return _thinkingChainService;
    }

    /// <summary>
    /// 文本润色
    /// </summary>
    public async Task<string> PolishTextAsync(string text, string style)
    {
        if (_currentProvider == null)
        {
            throw new InvalidOperationException("没有可用的AI服务提供者");
        }

        try
        {
            var prompt = $"请对以下文本进行润色，风格要求：{style}\n\n原文：\n{text}\n\n润色后的文本：";
            var enhancedPrompt = AddThinkingChainGuidance(prompt);
            var result = await _currentProvider.GenerateTextAsync(enhancedPrompt, 2000, 0.7f);

            if (_enableThinkingChainProcessing)
            {
                var filter = new ThinkingChainFilter
                {
                    EnableFilter = true,
                    Mode = FilterMode.RemoveThinkingChain
                };
                var processedResult = _thinkingChainService.ProcessThinkingChainResponse(result, filter);
                return processedResult.ProcessedContent;
            }

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "文本润色失败");
            throw;
        }
    }

    /// <summary>
    /// 文本扩展
    /// </summary>
    public async Task<string> ExpandTextAsync(string text, int targetLength, string? context = null)
    {
        if (_currentProvider == null)
        {
            throw new InvalidOperationException("没有可用的AI服务提供者");
        }

        try
        {
            var prompt = $"请将以下文本扩展到约{targetLength}字：\n\n原文：\n{text}\n\n";
            if (!string.IsNullOrEmpty(context))
            {
                prompt += $"上下文：\n{context}\n\n";
            }
            prompt += "扩展后的文本：";

            var enhancedPrompt = AddThinkingChainGuidance(prompt);
            var result = await _currentProvider.GenerateTextAsync(enhancedPrompt, targetLength * 2, 0.8f);

            if (_enableThinkingChainProcessing)
            {
                var filter = new ThinkingChainFilter
                {
                    EnableFilter = true,
                    Mode = FilterMode.RemoveThinkingChain
                };
                var processedResult = _thinkingChainService.ProcessThinkingChainResponse(result, filter);
                return processedResult.ProcessedContent;
            }

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "文本扩展失败");
            throw;
        }
    }

    /// <summary>
    /// 检查一致性
    /// </summary>
    public async Task<ConsistencyCheckResult> CheckConsistencyAsync(string content, string reference)
    {
        if (_currentProvider == null)
        {
            throw new InvalidOperationException("没有可用的AI服务提供者");
        }

        try
        {
            var prompt = $"请检查以下内容与参考资料的一致性：\n\n内容：\n{content}\n\n参考资料：\n{reference}\n\n一致性分析：";
            var enhancedPrompt = AddThinkingChainGuidance(prompt);
            var result = await _currentProvider.GenerateTextAsync(enhancedPrompt, 1000, 0.5f);

            string processedResult = result;
            if (_enableThinkingChainProcessing)
            {
                var filter = new ThinkingChainFilter
                {
                    EnableFilter = true,
                    Mode = FilterMode.RemoveThinkingChain
                };
                var processed = _thinkingChainService.ProcessThinkingChainResponse(result, filter);
                processedResult = processed.ProcessedContent;
            }

            // 简单解析结果
            var isConsistent = !processedResult.ToLower().Contains("不一致") && !processedResult.ToLower().Contains("矛盾");

            return new ConsistencyCheckResult
            {
                IsConsistent = isConsistent,
                ConfidenceScore = 0.8f,
                Issues = isConsistent ? new List<string>() : new List<string> { "发现一致性问题" },
                Suggestions = new List<string> { "建议进一步检查内容" }
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "一致性检查失败");
            throw;
        }
    }

    /// <summary>
    /// 生成大纲
    /// </summary>
    public async Task<string> GenerateOutlineAsync(string topic, string requirements)
    {
        if (_currentProvider == null)
        {
            throw new InvalidOperationException("没有可用的AI服务提供者");
        }

        try
        {
            var prompt = $"请为以下主题生成详细大纲：\n\n主题：{topic}\n\n要求：{requirements}\n\n大纲：";
            var enhancedPrompt = AddThinkingChainGuidance(prompt);
            var result = await _currentProvider.GenerateTextAsync(enhancedPrompt, 2000, 0.7f);

            if (_enableThinkingChainProcessing)
            {
                var filter = new ThinkingChainFilter
                {
                    EnableFilter = true,
                    Mode = FilterMode.RemoveThinkingChain
                };
                var processedResult = _thinkingChainService.ProcessThinkingChainResponse(result, filter);
                return processedResult.ProcessedContent;
            }

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "生成大纲失败");
            throw;
        }
    }

    /// <summary>
    /// 提取角色信息
    /// </summary>
    public async Task<List<CharacterInfo>> ExtractCharacterInfoAsync(string content)
    {
        if (_currentProvider == null)
        {
            throw new InvalidOperationException("没有可用的AI服务提供者");
        }

        try
        {
            var prompt = $"请从以下内容中提取角色信息：\n\n{content}\n\n角色信息：";
            var enhancedPrompt = AddThinkingChainGuidance(prompt);
            var result = await _currentProvider.GenerateTextAsync(enhancedPrompt, 1500, 0.6f);

            string processedResult = result;
            if (_enableThinkingChainProcessing)
            {
                var filter = new ThinkingChainFilter
                {
                    EnableFilter = true,
                    Mode = FilterMode.RemoveThinkingChain
                };
                var processed = _thinkingChainService.ProcessThinkingChainResponse(result, filter);
                processedResult = processed.ProcessedContent;
            }

            // 简单解析角色信息
            var characters = new List<CharacterInfo>();
            var lines = processedResult.Split('\n', StringSplitOptions.RemoveEmptyEntries);

            foreach (var line in lines)
            {
                if (line.Contains("姓名") || line.Contains("角色") || line.Contains("人物"))
                {
                    characters.Add(new CharacterInfo
                    {
                        Name = line.Trim(),
                        Description = "从文本中提取的角色信息"
                    });
                }
            }

            return characters;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "提取角色信息失败");
            throw;
        }
    }

    /// <summary>
    /// 从配置文件初始化AI服务提供者
    /// </summary>
    public async Task InitializeFromConfigFileAsync()
    {
        try
        {
            _logger.LogInformation("开始从配置文件初始化AI服务...");

            // 从配置服务获取配置
            var configService = _serviceProvider?.GetService<IAIModelConfigService>();
            if (configService != null)
            {
                var config = await configService.GetConfigAsync();
                await InitializeFromConfigAsync(config);
                _logger.LogInformation("从配置文件初始化AI服务成功");
            }
            else
            {
                _logger.LogWarning("配置服务不可用，使用默认初始化");
                await InitializeProvidersAsync();
                _logger.LogInformation("使用默认方式初始化AI服务完成");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "从配置文件初始化AI服务失败，使用默认配置");
            await InitializeProvidersAsync();
        }
    }

    /// <summary>
    /// 重新加载配置
    /// </summary>
    public async Task ReloadConfigurationAsync()
    {
        try
        {
            _logger.LogInformation("重新加载AI服务配置...");

            // 从配置服务获取最新的配置
            var configService = _serviceProvider?.GetService<IAIModelConfigService>();
            if (configService != null)
            {
                var config = await configService.GetConfigAsync();
                await InitializeFromConfigAsync(config);
            }
            else
            {
                // 如果没有配置服务，使用传统方式
                await InitializeProvidersAsync();
            }

            _logger.LogInformation("AI服务配置已重新加载");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "重新加载配置失败");
        }
    }

    /// <summary>
    /// 获取当前提供者的可用模型
    /// </summary>
    public async Task<List<AIModel>> GetCurrentProviderModelsAsync()
    {
        return await GetAvailableModelsAsync();
    }

    /// <summary>
    /// 确保AI服务可用
    /// </summary>
    private async Task EnsureServiceAvailableAsync()
    {
        // 定期健康检查
        if (DateTime.Now - _lastHealthCheck > _healthCheckInterval)
        {
            await PerformHealthCheckAsync();
            _lastHealthCheck = DateTime.Now;
        }

        if (_currentProvider == null)
        {
            _logger.LogWarning("当前没有AI服务提供者，尝试重新初始化");
            await InitializeFromConfigFileAsync();

            if (_currentProvider == null)
            {
                throw new InvalidOperationException("AI服务暂时不可用，请检查AI模型配置或稍后重试");
            }
        }

        // 检查当前提供者是否有可用模型
        try
        {
            var models = await _currentProvider.GetAvailableModelsAsync();
            if (!models.Any())
            {
                _logger.LogWarning("当前提供者没有可用模型，尝试重新加载");
                await ReloadConfigurationAsync();
            }
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "检查可用模型时发生错误，可能需要重新连接");
        }
    }

    /// <summary>
    /// 执行健康检查
    /// </summary>
    private async Task PerformHealthCheckAsync()
    {
        if (_currentProvider == null) return;

        try
        {
            _logger.LogDebug("执行AI服务健康检查");

            // 尝试获取可用模型列表作为健康检查
            var models = await _currentProvider.GetAvailableModelsAsync();

            if (!models.Any())
            {
                _logger.LogWarning("健康检查失败：没有可用模型");
            }
            else
            {
                _logger.LogDebug($"健康检查通过：发现 {models.Count} 个可用模型");
            }
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "AI服务健康检查失败");

            // 健康检查失败时尝试重新连接
            await TryRecoverServiceAsync(ex);
        }
    }

    /// <summary>
    /// 尝试恢复AI服务
    /// </summary>
    private async Task<bool> TryRecoverServiceAsync(Exception originalException)
    {
        try
        {
            _logger.LogInformation("尝试恢复AI服务...");

            // 检查是否是连接相关的错误
            if (IsConnectionError(originalException))
            {
                _logger.LogInformation("检测到连接错误，尝试重新初始化服务");
                await ReloadConfigurationAsync();

                // 验证服务是否恢复
                if (_currentProvider != null)
                {
                    var models = await _currentProvider.GetAvailableModelsAsync();
                    if (models.Any())
                    {
                        _logger.LogInformation("AI服务恢复成功");
                        return true;
                    }
                }
            }

            _logger.LogWarning("AI服务恢复失败");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "尝试恢复AI服务时发生错误");
            return false;
        }
    }

    /// <summary>
    /// 判断是否是连接相关的错误
    /// </summary>
    private bool IsConnectionError(Exception ex)
    {
        var message = ex.Message.ToLower();
        return message.Contains("connection") ||
               message.Contains("timeout") ||
               message.Contains("network") ||
               message.Contains("badgateway") ||
               message.Contains("502") ||
               message.Contains("服务暂时不可用") ||
               ex is HttpRequestException ||
               ex is TaskCanceledException;
    }

    /// <summary>
    /// 从配置对象初始化AI服务
    /// </summary>
    private async Task InitializeFromConfigAsync(AIModelConfig config)
    {
        try
        {
            _logger.LogInformation($"从配置初始化AI服务 - 平台: {config.Platform}");

            // 清除现有提供者
            _providers.Clear();
            _currentProvider = null;
            _currentModel = null;

            // 初始化Ollama服务
            if (config.OllamaConfig != null && !string.IsNullOrEmpty(config.OllamaConfig.BaseUrl))
            {
                var ollamaService = new OllamaService(CreateConfigurationSection("AI:Ollama", new Dictionary<string, string>
                {
                    ["BaseUrl"] = config.OllamaConfig.BaseUrl
                }), _logger);
                _providers["Ollama"] = ollamaService;
                _logger.LogInformation("Ollama服务已初始化");
            }

            // 初始化LM Studio服务
            if (config.LMStudioConfig != null && !string.IsNullOrEmpty(config.LMStudioConfig.BaseUrl))
            {
                var lmStudioService = new LMStudioService(CreateConfigurationSection("AI:LMStudio", new Dictionary<string, string>
                {
                    ["BaseUrl"] = config.LMStudioConfig.BaseUrl
                }), _logger);
                _providers["LMStudio"] = lmStudioService;
                _logger.LogInformation("LM Studio服务已初始化");
            }

            // 初始化智谱AI服务
            if (config.ZhipuAIConfig != null && !string.IsNullOrEmpty(config.ZhipuAIConfig.ApiKey))
            {
                var zhipuService = new ZhipuAIService(CreateConfigurationSection("AI:ZhipuAI", new Dictionary<string, string>
                {
                    ["ApiKey"] = config.ZhipuAIConfig.ApiKey,
                    ["BaseUrl"] = config.ZhipuAIConfig.BaseUrl ?? "https://open.bigmodel.cn/api/paas/v4",
                    ["DefaultModel"] = config.ZhipuAIConfig.Model ?? "GLM-4-Flash-250414"
                }), _logger);
                _providers["ZhipuAI"] = zhipuService;
                _logger.LogInformation("智谱AI服务已初始化");
            }

            // 初始化DeepSeek服务
            if (config.DeepSeekConfig != null && !string.IsNullOrEmpty(config.DeepSeekConfig.ApiKey))
            {
                var deepSeekService = new DeepSeekService(CreateConfigurationSection("AI:DeepSeek", new Dictionary<string, string>
                {
                    ["ApiKey"] = config.DeepSeekConfig.ApiKey,
                    ["BaseUrl"] = config.DeepSeekConfig.BaseUrl ?? "https://api.deepseek.com",
                    ["DefaultModel"] = config.DeepSeekConfig.Model ?? "deepseek-chat"
                }), _logger);
                _providers["DeepSeek"] = deepSeekService;
                _logger.LogInformation("DeepSeek服务已初始化");
            }

            // 初始化OpenAI服务
            if (config.OpenAIConfig != null)
            {
                var openAIService = new OpenAIService(CreateConfigurationSection("AI:OpenAI", new Dictionary<string, string>
                {
                    ["ApiKey"] = config.OpenAIConfig.ApiKey ?? "",
                    ["BaseUrl"] = config.OpenAIConfig.BaseUrl ?? "https://api.openai.com/v1",
                    ["Model"] = config.OpenAIConfig.Model ?? "gpt-3.5-turbo"
                }), _logger);
                _providers["OpenAI"] = openAIService;
                _logger.LogInformation("OpenAI服务已初始化");
            }

            // 初始化Alibaba服务
            if (config.AlibabaConfig != null && !string.IsNullOrEmpty(config.AlibabaConfig.ApiKey))
            {
                var alibabaService = new AlibabaService(CreateConfigurationSection("AI:Alibaba", new Dictionary<string, string>
                {
                    ["ApiKey"] = config.AlibabaConfig.ApiKey,
                    ["BaseUrl"] = config.AlibabaConfig.BaseUrl ?? "https://dashscope.aliyuncs.com/api/v1",
                    ["Model"] = config.AlibabaConfig.Model ?? "qwen-turbo"
                }), _logger);
                _providers["Alibaba"] = alibabaService;
                _logger.LogInformation("Alibaba服务已初始化");
            }

            // 初始化RWKV服务
            if (config.RWKVConfig != null && !string.IsNullOrEmpty(config.RWKVConfig.BaseUrl))
            {
                try
                {
                    var httpClient = _serviceProvider?.GetService<HttpClient>() ?? new HttpClient();
                    var rwkvLogger = _serviceProvider?.GetService<ILogger<RWKVService>>() ??
                                   Microsoft.Extensions.Logging.Abstractions.NullLogger<RWKVService>.Instance;
                    var rwkvService = new RWKVService(rwkvLogger, httpClient);
                    rwkvService.UpdateConfig(config.RWKVConfig);
                    _providers["RWKV"] = rwkvService;
                    _logger.LogInformation("RWKV服务已初始化");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "初始化RWKV服务失败");
                }
            }

            // 设置当前提供者和模型
            await SetCurrentProviderAndModelFromConfigAsync(config);

            _logger.LogInformation($"从配置初始化AI服务完成，共初始化 {_providers.Count} 个提供者");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "从配置初始化AI服务失败");
        }
    }

    /// <summary>
    /// 从配置设置当前提供者和模型
    /// </summary>
    private async Task SetCurrentProviderAndModelFromConfigAsync(AIModelConfig config)
    {
        try
        {
            // 设置当前提供者
            if (!string.IsNullOrEmpty(config.Platform) && _providers.ContainsKey(config.Platform))
            {
                _currentProvider = _providers[config.Platform];
                _logger.LogInformation($"设置当前AI提供者: {config.Platform}");

                // 设置当前模型
                string? selectedModel = GetSelectedModelFromConfig(config);
                if (!string.IsNullOrEmpty(selectedModel))
                {
                    _logger.LogInformation($"尝试设置模型: {selectedModel}");

                    // 等待一下让服务完全初始化
                    await Task.Delay(1000);

                    var success = await _currentProvider.SetCurrentModelAsync(selectedModel);
                    if (success)
                    {
                        _currentModel = _currentProvider.GetCurrentModel();
                        _logger.LogInformation($"成功设置当前模型: {selectedModel}");
                    }
                    else
                    {
                        _logger.LogWarning($"设置模型失败: {selectedModel}，尝试使用第一个可用模型");
                        await TrySetFirstAvailableModelAsync();
                    }
                }
                else
                {
                    _logger.LogInformation("配置中没有指定模型，尝试使用第一个可用模型");
                    await TrySetFirstAvailableModelAsync();
                }
            }
            else if (_providers.Any())
            {
                // 如果配置的平台不可用，使用第一个可用的提供者
                _currentProvider = _providers.Values.First();
                _logger.LogWarning($"配置的平台 {config.Platform} 不可用，使用第一个可用的提供者: {_providers.Keys.First()}");
                await TrySetFirstAvailableModelAsync();
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "设置当前提供者和模型失败");
        }
    }

    /// <summary>
    /// 从配置获取选中的模型
    /// </summary>
    private string? GetSelectedModelFromConfig(AIModelConfig config)
    {
        return config.Platform switch
        {
            "Ollama" => config.OllamaConfig?.SelectedModel,
            "LMStudio" => config.LMStudioConfig?.SelectedModel,
            "ZhipuAI" => config.ZhipuAIConfig?.Model,
            "DeepSeek" => config.DeepSeekConfig?.Model,
            "OpenAI" => config.OpenAIConfig?.Model,
            "Alibaba" => config.AlibabaConfig?.Model,
            "RWKV" => config.RWKVConfig?.SelectedModel,
            _ => null
        };
    }

    /// <summary>
    /// 尝试设置第一个可用模型
    /// </summary>
    private async Task TrySetFirstAvailableModelAsync()
    {
        try
        {
            if (_currentProvider != null)
            {
                var availableModels = await _currentProvider.GetAvailableModelsAsync();
                if (availableModels.Any())
                {
                    var firstModel = availableModels.First();
                    var success = await _currentProvider.SetCurrentModelAsync(firstModel.Id);
                    if (success)
                    {
                        _currentModel = _currentProvider.GetCurrentModel();
                        _logger.LogInformation($"使用第一个可用模型: {firstModel.Name} ({firstModel.Provider})");
                    }
                    else
                    {
                        // 即使设置失败，也记录当前模型信息
                        _currentModel = firstModel;
                        _logger.LogInformation($"设置为第一个可用模型（未验证）: {firstModel.Name}");
                    }
                }
                else
                {
                    _logger.LogWarning($"当前提供者 {_currentProvider.GetType().Name} 没有可用模型");
                }
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "设置第一个可用模型失败");
        }
    }

    /// <summary>
    /// 创建配置节
    /// </summary>
    private IConfiguration CreateConfigurationSection(string sectionName, Dictionary<string, string> values)
    {
        var configBuilder = new ConfigurationBuilder();
        var keyValuePairs = values.Select(kvp => new KeyValuePair<string, string?>(kvp.Key, kvp.Value));
        configBuilder.AddInMemoryCollection(keyValuePairs);
        return configBuilder.Build();
    }
}
